package com.scm.controllor;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.scm.dao.OPscmUser;
import com.scm.model.ScmUser;

public class UserMain extends HttpServlet
{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		int[] p = { 1, 0 };
		final int pageNow = 0;
		final int pageCount = 1;
		String pn = req.getParameter("pageNow");
		String flag = req.getParameter("flag");
		if (pn != null)
			p[pageNow] = Integer.parseInt(pn);

		if (flag == null)
			flag = "separate";

		// 分页
		if (flag.equals("separate")) {
			OPscmUser scmUser = new OPscmUser();

			ArrayList<ScmUser> al = scmUser.getResultset(p);

			req.setAttribute("scmuser", al);
			// 重要 后面的""
			req.setAttribute("page_now", p[pageNow]);
			req.setAttribute("page_count", p[pageCount]);

			req.getRequestDispatcher("/User/userMain.jsp").forward(
					req, resp);
		}
		// 删除
		if (flag.equals("del_user")) {

			String id = req.getParameter("userid");
			OPscmUser scmUser = new OPscmUser();

			if (scmUser.delUserById(id)) {
				// ok
				resp.sendRedirect("success.jsp");
			} else {
				resp.sendRedirect("err.jsp");
			}

		}
		// 修改
		if (flag.equals("mod")) {
			
			String account = req.getParameter("mod_account");
			String password = req.getParameter("mod_password");
			String name = req.getParameter("mod_name");
			String status = req.getParameter("mod_status");
			OPscmUser oPscmUser = new OPscmUser();

			ScmUser scmUser=new ScmUser();
			scmUser.setAccount(account);
			scmUser.setPassword(password);
			scmUser.setName(name);
			scmUser.setStatus(status);
			if (oPscmUser.modById(scmUser)) {
				// ok
				resp.sendRedirect("success.jsp");
			} else {
				resp.sendRedirect("err.jsp");
			}

		}
		// 添加
		if (flag.equals("add")) {

			String account = req.getParameter("user_account");
			String password = req.getParameter("user_password");
			String name = req.getParameter("user_name");
			String createdate = req.getParameter("user_createdate");
			String status = req.getParameter("user_status");
			OPscmUser opScmUser = new OPscmUser();
			
			ScmUser scmUser=new ScmUser();
			scmUser.setAccount(account);
			scmUser.setPassword(password);
			scmUser.setName(name);
			scmUser.setCreatedate(createdate);
			scmUser.setStatus(status);

			if (opScmUser.add(scmUser)) {
				// ok
				resp.sendRedirect("success.jsp");
			} else {
				resp.sendRedirect("err.jsp");
			}

		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		doGet(req, resp);
	}

}
